package com.zzmcc.wechat.action;

import com.zzmcc.wechat.entity.UserInfo;
import com.zzmcc.wechat.oauth.Oauth;
import com.zzmcc.wechat.oauth.User;
import com.zzmcc.wechat.util.Tools;
import org.smart4j.framework.mvc.DataContext;
import org.smart4j.framework.mvc.annotation.Action;
import org.smart4j.framework.mvc.annotation.Request;
import org.smart4j.framework.mvc.bean.Params;
import org.smart4j.framework.mvc.bean.Result;
import org.smart4j.framework.mvc.bean.View;

import org.smart4j.framework.util.CastUtil;
import org.smart4j.framework.util.StringUtil;
import org.smart4j.plugin.security.SecurityHelper;
import org.smart4j.plugin.security.fault.LoginException;

import java.util.Map;


@Action
public class SystemAction {

    @Request.Get("/login")
    public View login() {
        return new View("login.jsp");
    }
    @Request.Get("/oauth")
    public View oauth(Params params){
        String code=params.getString("code");
        String state=params.getString("state");

        if ((code.toLowerCase().equals("authdeny"))){
            return  new View("login.jsp");
        }
        else{
            String appid="wx13299d5a69b39723";
            String secret="2ac824248c90219af2d4426bcf1f06a6";
            Oauth oauth=new Oauth(appid,secret);
            Map<String,Object>  tokenMap = oauth.getToken(code);
            String openid= CastUtil.castString(tokenMap.get("openid"));
            String access_token =CastUtil.castString(tokenMap.get("access_token"));
            User user =new User();
            UserInfo userInfo = user.getUserInfo(access_token,openid);
            DataContext.Request.put("userInfo", userInfo);
            return new View("welcome.jsp");
        }

    }
    @Request.Post("/login")
    public Result login(Params params) {
        String username = params.getString("username");
        String password = params.getString("password");

        try {
            SecurityHelper.login(username, password, false);
        } catch (LoginException e) {
            return new Result(false);
        }

        return new Result(true);
    }

    @Request.Get("/logout")
    public Result logout() {
        SecurityHelper.logout();
        return new Result(true);
    }

    @Request.Get("/admin")
    public View manage(){
        return  new View("admin/index.jsp");
    }


    @Request.Get("/post")
    public  View doPost(){
        return new View("post.jsp");
    }

    @Request.Get("/vm")
    public View vm(){
        String[] hobbyArray={"吃饭","喝水","洗澡"};
        return new View("vm/test.vm").data("name", "张三")
                .data("hobby", "爱好")
                .data("hobbyArray", hobbyArray);
    }

    @Request.Get("/vm/admin")
    public View admin(){
        return  new View("vm/admin/index.vm").data("name","管理页面");
    }


}
